typedef struct {
	    MYSQL **connections;  // 连接数组
	        int size;            // 池大小
		    int used;            // 已用连接数
		        pthread_mutex_t lock;// 线程锁
} ConnectionPool;


ConnectionPool* pool_init(int size, const char* host, const char* user, const char* pwd, const char* db) {
	    ConnectionPool *pool = malloc(sizeof(ConnectionPool));
	        pool->connections = malloc(size * sizeof(MYSQL*));
		    
		    for (int i = 0; i < size; i++) {
			            MYSQL *conn = mysql_init(NULL);
				            if (!mysql_real_connect(conn, host, user, pwd, db, 0, NULL, 0)) {
						                fprintf(stderr, "Connection failed: %s\n", mysql_error(conn));
								            exit(1);
									            }
					            pool->connections[i] = conn;
						        }
		        
		        pool->size = size;
			    pool->used = 0;
			        pthread_mutex_init(&pool->lock, NULL);
				    return pool;
}

MYSQL* pool_get_connection(ConnectionPool *pool) {
	    pthread_mutex_lock(&pool->lock);
	        
	        if (pool->used >= pool->size) {
			        pthread_mutex_unlock(&pool->lock);
				        return NULL; // 连接池耗尽
					    }
		    
		    MYSQL *conn = pool->connections[pool->used++];
		        

		        if (mysql_ping(conn) != 0) {
				        mysql_close(conn);
					        conn = mysql_init(NULL);
						        mysql_real_connect(conn, ...); // 重新连接
							        pool->connections[pool->used-1] = conn; // 替换失效连接
								    }
			    
			    pthread_mutex_unlock(&pool->lock);
			        return conn;
}
